<template>
  <div class="">
    <van-nav-bar left-arrow @click-left="onClickLeft" />
    <div class="verify">
      <p class="verify-title">输入四位验证码</p>
      <p class="verify-txt">已发送验证码至+86&nbsp;{{ phone }}</p>
      <!-- 密码输入框 -->
      <van-password-input
        gutter="20"
        length="4"
        :mask="false"
        :value="value"
        :focused="showKeyboard"
        @focus="showKeyboard = true"
      />
      <!-- 数字键盘 -->
      <van-number-keyboard
        v-model="value"
        :show="showKeyboard"
        @blur="showKeyboard = false"
      />
      <div class="count">
        <van-count-down :time="time" format=" ss s" />
        <span class="count-txt">后重新发送验证码</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { SmsgetLoginApi, postRegisterApi } from "../utils/api";
import { Toast } from "vant";
export default {
  setup() {
    const router = useRouter();
    const onClickLeft = () => {
      router.go(-1);
    };
    const store = useStore();
    const phone = store.state.phone;
    // console.log(phone);
    const value = ref("");
    const showKeyboard = ref(true);
    const time = ref(60 * 1000);
    watch(value, () => {
      if (value.value.length === 4) {
        postRegisterApi({
          phone: phone,
          code: value.value,
        }).then((res) => {
          if (res.status === "0") {
            SmsgetLoginApi({
              phone: phone,
            }).then((res) => {
              if (res.status === 0) {
                Toast.success(res.msg);
                router.replace("/home");
                sessionStorage.setItem("token", res.token);
              }
            });
          } else {
            Toast.fail("验证码错误");
          }
        });
      }
    });

    return {
      value,
      showKeyboard,
      phone,
      time,
      onClickLeft,
    };
  },
};
</script>

<style lang="less">
.verify {
  padding: 30px 40px 0;

  .verify-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 15px;
  }
  .verify-txt {
    font-size: 16px;
    color: #666;
    margin-bottom: 30px;
  }
  .van-password-input__security li {
    border: 1px solid #333;
    border-radius: 5px;
  }
  .count {
    font-size: 14px;
    display: flex;
    justify-items: center;
    float: right;
    margin-top: 40px;
    margin-right: 20px;
  }
}
</style>
